package main

import (
	"log"
	// 引入 mysql, gorm
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
)

// User 用户测试
type User struct {
	gorm.Model
	Username string `json:"username"`
	Password string `json:"password"`
}

// TableName 表名
func (user User) TableName() string {
	return "user"
}

// 测试 gorm 的时候
func main() {
	// 数据库的语言设置： charset=utf8
	db, err := gorm.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/golang?charset=utf8&parseTime=True")

	db.LogMode(true)

	if err != nil {
		log.Panicln("failed to connect database: ", err.Error())
	}

	defer db.Close()

	if !db.HasTable(User{}) {
		db.CreateTable(User{})
	}

	var user1 User
	var user2 User

	db.First(&user1, 5)

	log.Printf("user 1 is %+v\n", user1)

	db.First(&user2, "username = ?", "santiiny")
	log.Printf("user 1 is %+v\n", user2)
	log.Println(user2)
	log.Println(user2.ID)
	log.Println(user2.Username)
}
